<template>
  <div class="department-container">
    <div class="app-container">
      <el-tabs v-model="activeName">
        <el-tab-pane label="角色管理" name="first">
          <!-- 按钮 -->
          <div class="btn-wrap">
            <el-button type="primary" @click="addRoleBtn">新增角色</el-button>
          </div>
          <!-- table表格的位置 -->
          <div>
            <el-table
              :data="tableData"
              border
              style="width: 100%"
            >
              <el-table-column
                label="序号"
                type="index"
                width="50"
              />
              <el-table-column
                prop="name"
                label="角色"
                width="300"
              />
              <el-table-column
                prop="description"
                label="描述"
              />
              <el-table-column
                label="操作"
                width="400"
              >
                <template slot-scope="scope">
                  <el-button type="primary" size="mini" @click="assignPermission(scope.row.id)">分配权限</el-button>
                  <el-button type="success" size="mini" @click="editRoleBtn(scope)">编辑</el-button>
                  <el-button type="danger" size="mini" @click="deleteRoleBtn(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!-- 分页插件的位置 -->
          <div class="pagin-wrap">
            <el-pagination
              :current-page.sync="form.page"
              :page-sizes="[2, 4, 6, 8]"
              :page-size="10"
              layout="prev, pager, next, total, sizes"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane label="配置管理" name="second">分配权限</el-tab-pane>
        <el-tab-pane label="角色管理" name="third">编辑</el-tab-pane>
        <el-tab-pane label="定时任务补偿" name="fourth">删除</el-tab-pane>
      </el-tabs>
    </div>
    <!-- 对话框最后会放在body上面，源码 document.body.appendChild(modal) -->
    <el-dialog
      :title="isEdit ? '编辑角色' : '新增角色' "
      :visible.sync="dialogVisible"
      width="30%"
      @close="dialogCloseBtn"
    >
      <el-form ref="formRef" :model="formDialog" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formDialog.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="formDialog.description" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">{{ isEdit ? '编辑' : '新增' }}</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配权限的弹出框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="dialogPermissionVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <AssignPermission v-if="dialogPermissionVisible" :current-id="currentId" @close="dialogPermissionVisible = false" />
    </el-dialog>
  </div>
</template>

<script>
import { getRolesListRequest, addRolesRequest, updateRoleByIdRequest, deleteRoleByIdRequest } from '@/api/setting'
import AssignPermission from './AssignPermission.vue'
import _ from 'lodash'
export default {
  name: 'SettingsCom',
  components: { AssignPermission },
  data() {
    return {
      activeName: 'first',
      tableData: [],
      form: {
        page: 1,
        pagesize: 2
      },
      dialogVisible: false,
      formDialog: {
        name: '',
        description: ''
      },
      total: 0,
      isEdit: false,
      rules: {
        name: { required: true, message: '请输入角色名称', trigger: 'blur' },
        description: { required: true, message: '请输入角色描述', trigger: 'blur' }
      },
      // 权限弹出框的显示隐藏
      dialogPermissionVisible: false,
      currentId: ''
    }
  },
  computed: {
    // 最大的页码值： 一共5项  每页显示2条  5/2 = 2.5  3页
    maxPageNum() {
      return Math.ceil(this.total / this.form.pagesize)
    },
    // 最后一页是否填满
    isLastPageFull() {
      return this.total % this.form.pagesize === 0
    }
  },
  created() {
    this.getRolesList()
    // 这里加不加 await 都可以， 取决于下面代码是否依赖上面代码的完成
  },
  methods: {
    async getRolesList() {
      try {
        const res = await getRolesListRequest(this.form)
        if (res.success) {
          this.tableData = res.data.rows
          this.total = res.data.total
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        this.$message.error('获取角色列表失败')
      }
    },
    handleSizeChange(value) {
      // 每页显示条数的改变
      this.form.page = 1
      this.form.pagesize = value
      this.getRolesList()
    },
    handleCurrentChange(value) {
      // 页码值的改变
      this.form.page = value
      this.getRolesList()
    },
    // 页面上新增的按钮
    addRoleBtn() {
      this.dialogVisible = true
      // 将isEdit变量 赋值为 false
      this.isEdit = false
    },
    async addRoles() {
      try {
        const res = await addRolesRequest(this.formDialog)
        if (res.success) {
          // 有个注意点： 如果最后一页已经满了，那么应该将总数量添加1，在跳转到下一页
          // 因为在判断的时候涉及到动态数据， 所有将最大的页面值，还有最后一页是否填满了，应该使用计算属性来写
          if (this.isLastPageFull) {
            this.form.page = this.maxPageNum + 1
            this.total++
          } else {
            this.form.page = this.maxPageNum
          }
          // 1 关闭弹框  2. 刷新后面的列表页面
          this.dialogVisible = false
          this.getRolesList()
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        this.$message.error('添加角色失败')
      }
    },
    // 封装一个编辑请求
    async updateRoleById() {
      try {
        const res = await updateRoleByIdRequest(this.formDialog)
        console.log('请求成功: ', res)
        if (res.success) {
          this.dialogVisible = false
          this.getRolesList()
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        console.log('编辑请求出错')
      }
    },
    onSubmit() {
      // console.log(this.formDialog)
      // 发请求之前，需要先校验所有逇字段是否通过了前端校验， 然后再发请求
      this.$refs.formRef.validate(val => {
        if (val) {
          if (this.isEdit) {
            this.updateRoleById()
          } else {
            this.addRoles()
          }
        }
      })
    },
    editRoleBtn(scope) {
      // 打开弹出窗
      this.dialogVisible = true
      // 回填数据
      this.formDialog = _.cloneDeep(scope.row)
      // 将isEdit变量赋值为true
      this.isEdit = true
    },
    dialogCloseBtn() {
      console.log(this.$options.data())
      // 既可以清除表单的校验， 又可以初始化一部分数据
      this.$refs.formRef.resetFields()
      if (this.isEdit) {
        this.formDialog = this.$options.data().formDialog
        // this.formDialog = this.$options.data.call(this).formDialog
      }
    },
    async deleteRoleById(id) {
      try {
        const res = await deleteRoleByIdRequest(id)
        if (res.success) {
          this.$message({
            type: 'success',
            message: '删除请求成功'
          })
          // 如果当前页面只剩下一条数据，我们应该吧页码值 向上走一页，将page-1
          if (this.tableData.length === 1) {
            this.form.page--
            if (this.form.page <= 0) {
              this.form.page = 1
            }
          }
          this.getRolesList()
        }
      } catch (error) {
        this.$message({
          type: 'info',
          message: '删除请求失败'
        })
      }
    },
    deleteRoleBtn(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteRoleById(id)
        // 下面这个提示，地方不对，应该是删除请求成以后，在给提示
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    assignPermission(id) {
      this.dialogPermissionVisible = true
      // 当前点击的元素的id
      this.currentId = id
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  border: 1px solid red;
  ::v-deep .btn-wrap {
    margin: 15px 0;
  }
  .pagin-wrap {
    margin-top: 15px;
    text-align: right;
  }
}
</style>
